import React, { Component } from 'react';
import { Modal, Button } from 'antd';
import _ from 'underscore';

const FormModal = (Wrapper) => {
  class WrapperComponent extends Component {
    constructor(props) {
      super(props);
      this.state = {
        key: +new Date(),
      };
    }

    componentWillMount() {
      if (!_.isEmpty(this.props.fieldErrors)) {
        this.handleError(this.props.fieldErrors);
      }
    }

    componentWillReceiveProps(nextProps) {
      if (!_.isEqual(this.props.fieldErrors, nextProps.fieldErrors)) {
        this.handleError(nextProps.fieldErrors, nextProps.form.getFieldsValue());
      }

      if (nextProps.visible !== this.props.visible) {
        this.setState({
          key: +new Date()
        });
      }
    }

    doSubmit = () => {
      this.props.form.validateFields(
        { force: true },
        (err, values) => {
          if (!err) {
            this.props.onSubmit(values);
          }
        },
      );
    }

    handleSubmit = (e) => {
      e.preventDefault();
      this.doSubmit();
    }

    componentDidMount = () => {
      if (this.props.autoSubmit) {
        this.doSubmit();
      }
    }

    handleError(errors, fields) {
      const fieldErrors = _.mapObject(
        errors,
        (item, key) => ({ errors: [item] })
      );

      if (fields) {
        const fieldsReset = _.mapObject(fieldErrors,
          (item, key) => {
            const errors = item.errors;
            let keys = key.split('.');
            let topKey = keys[0];
            let subKey = keys[1];
            let value = subKey ? fields[topKey][subKey] : fields[topKey];
            return {
              value,
              errors,
            };
          },
        );

        this.props.form.setFields(fieldsReset);
      } else {
        this.props.form.setFields(fieldErrors);
      }
    }

    render() {
      const formItemLayout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 14 },
      };
      return (
        <Modal
          key={ this.state.key }
          visible={ this.props.visible }
          title={ this.props.title }
          onCancel={ this.props.onCancel }
          footer={ false }
          wrapClassName="vertical-center-modal form-modal"
          width={ this.props.width }
          height={ this.props.height }
          maskClosable={ false }
        >
          <Wrapper
            {...this.props}
            formItemLayout={ formItemLayout }
            onSubmit={ this.handleSubmit }
          />
          <div className="modal-bottom-bar clearfix">
            <div className="btn-wrap cancel-btn">
              <Button onClick={this.props.onCancel} >取消</Button>
            </div>
            <div className="btn-wrap">
              <Button onClick={this.handleSubmit} >提交</Button>
            </div>
          </div>
        </Modal>
      );
    }
  }

  return WrapperComponent;
};

export default FormModal;
